package com.lsp.rocketmqprovider.listener;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

import java.util.HashMap;
import java.util.Map;

/**
 *在RocketMQ-Spring 2.1.0 版本之后，注解RocketMQTransactionListener不能设置txProducerGroup、ak、sk，
 * 只能在同一个RocketMQLocalTransactionListener根据参数判断执行不同的本地事务
 */
@RocketMQTransactionListener
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {

    private static Map<String, RocketMQLocalTransactionState> STATE_MAP = new HashMap<>();

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {

        try {
            STATE_MAP.put(message.getHeaders().getId().toString(),RocketMQLocalTransactionState.COMMIT);
//            int i =1/0;
            System.out.printf("事务已经提交 %s",STATE_MAP);
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            System.out.println("事务异常");
        }
        STATE_MAP.put(message.getHeaders().getId().toString(),RocketMQLocalTransactionState.UNKNOWN);
        System.out.printf("事务未处理 %s",STATE_MAP);
        return RocketMQLocalTransactionState.UNKNOWN;

    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        return STATE_MAP.get(message.getHeaders().getId().toString());
    }
}
